package com.iflytek.rule.strategy.valueengine;

import com.iflytek.rule.utils.Utils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.Map;

/**
 * @Author weibi
 * @Date 2020/3/3 17:08
 * @Version 1.0
 * @Description 格式：js#方法#代码#参数#参数 ，js统一有返回值
 **/
public class JsValueEngine implements IValueEngine {

    @Override
    public Object process(Map<String, Object> map,
                          Object object,
                          String value) {

        String[] arr = value.split("\\#");
        String[] param = createJsParam(map, object, value);
        return jsObjFunc(arr[2], arr[1], param);
    }

    /**
     * 获取js入参
     *
     * @param value
     * @return
     */
    private String[] createJsParam(Map<String, Object> map,
                                   Object object, String value) {

        int count = 0;
        String res = "";
        for (int i = 0; i < value.length(); i++) {
            if ("#".equals(String.valueOf(value.charAt(i)))) {
                count++;
                if (3 == count) {
                    res = value.substring(i + 1);
                    break;
                }
            }
        }

        if ("".equals(res)) {
            return new String[0];
        }

        String[] resArr = res.split("\\#");
        String[] result = new String[resArr.length];
        for (int p = 0; p < resArr.length; p++) {
            String st = Utils.toStr(resArr[p], map, object);
            result[p] = st;
        }
        return result;
    }


    /**
     * 执行 js 代码
     *
     * @param jsStr    js 代码串
     * @param function 方法
     * @param args     参数
     * @return
     */
    public static Object jsObjFunc(String jsStr, String function, Object... args) {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine scriptEngine = sem.getEngineByName("js");
        try {
            scriptEngine.eval(jsStr);
            Invocable inv2 = (Invocable) scriptEngine;
            return inv2.invokeFunction(function, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {

//        JsValueEngine engine = new JsValueEngine();
//
//        String value = "js#a#function a(x,y){\n" +
//                "  return parseInt(x)+parseInt(y);\n" +
//                "}#1#2";
//        String[] arr = value.split("\\#");
//        String[] param = engine.createJsParam(value);
//        System.out.println(jsObjFunc(arr[2], arr[1], param));
    }
}
